package com.ericpol.selenium;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

public class Page {

	protected WebDriver driver;
	//private String baseUrl;
	private StringBuffer verificationErrors = new StringBuffer();

	public Page() {
		super();
	}

	@BeforeMethod
	public void setUp() throws Exception {
		openAndSetBrowser();
	}

	protected void checkEqualsString(String assertText, String givenText) {
		assertEquals(assertText, givenText);
	}

	protected void openPage(String subPage) {
		driver.get(subPage);
	}

	private void openAndSetBrowser() {
		driver = new FirefoxDriver();
//		baseUrl = base;
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	protected String findAndGetText(By text) {
		return driver.findElement(text).getText();
	}

	protected Boolean assertTextPresent(By by, String text) {
		WebElement element = driver.findElement(by);
		assertEquals(text, element.getText());
		System.out.println("Sprawdzanie textu");
		return true;
	}

	protected void checkPageTitle(String address) {
		assertEquals(address, driver.getTitle());
	}

	protected void findAndClick(By text) {
		driver.findElement(text).click();
	}
	
	protected void insertText(By by, String text){  //to input texts into edit boxes
		WebElement element = driver.findElement(by);
		element.clear();
		element.sendKeys(text);
	}

	@AfterMethod
	public void tearDown() throws Exception {
		quitBrowser();
	}

	private void quitBrowser() {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

	private boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}

}